﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;

namespace Simhopp.Common
{
    public static class CompetitionMap
    {
        public static int SaveCompetitionToDatabase(Competition competition)
        {
            var oldCompetition = ReadCompetition.ReadCompetitionById(competition.Id);

            foreach (var judge in oldCompetition.Judges)
            {
                if (!competition.Judges.Contains(judge) && judge.AccountType != AccountTypes.Administrator)
                    UserMap.RemoveUserFromDataBase(judge);
            }

            foreach (var diver in oldCompetition.Participants)
            {
                if(!competition.Participants.Contains(diver))
                DiverMap.RemoveDiverFromDatabase(diver);
            }

            var id = GenericMap.SaveObjectToDatabase(competition);
            foreach (var judge in competition.Judges)
                UserMap.SaveUserToDatabase(judge);
            foreach (var dive in competition.Participants)
                DiverMap.SaveDiverToDatabase(dive);
            return id;
        }

        public static List<Competition> ReadAllCompetitionsFromDatabase()
        {
            var dictionary = GenericMap.ReadAllObjectsFromDatabase(typeof(Competition));
            try
            {
                var competitions = dictionary.Select(Competition.GetFromDictionary).ToList();
                MyLogger.Debug("All dictionaries converted to Competition-objects");
                return competitions;
            }
            catch (Exception e)
            {
                MyLogger.Error("Could not convert all dictionaries to Competition-objects - " + e.Message);
                return null;
            }
        }

        public static void RemoveCompetitionFromDatabase(Competition competition)
        {
            GenericMap.RemoveObjectFromDatabase(competition);
        }

        public static Competition ReadCompetitionFromDatabase(int id)
        {
            var dbResult = GenericMap.ReadObjectFromDatabase(id, typeof(Competition));
            return dbResult == null ? null : Competition.GetFromDictionary(dbResult);
        }
    }
}
